import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:guochaoapp/common/constant/api.dart';
import 'package:guochaoapp/common/utils/http_client.dart';
import 'package:guochaoapp/common/widges/dialog.dart';
import 'package:guochaoapp/generated/json/base/json_convert_content.dart';
import 'package:guochaoapp/model/cart_entity.dart';
import 'package:guochaoapp/model/cart_settle_entity.dart';
import 'package:guochaoapp/routes/app_pages.dart';
import 'package:guochaoapp/services/user_service.dart';

import '../../r.dart';
import '../tabbar_controller.dart';

class GCShoppingController extends GetxController {
  UserService userService = Get.find();

  var cartList = RxList<CartData>.empty();
  var checkAllSelected = false.obs;
  var chooseList = <CartDataItemList>[];
  int skuTotal = 0;

  List<List<TextEditingController>> textEditingControllers = [];

  int originNum;
  int editX;
  int editY;
  CartDataItemList editSku;
  bool editChanged;

  String checkedMoney() {
    double res = 0.0;
    chooseList.forEach((e) {
      res += e.price * e.num;
    });

    return res.toStringAsFixed(2);
  }

  String checkedWeight() {
    double res = 0.0;
    chooseList.forEach((e) {
      res += e.weight * e.num;
    });
    if (res >= 1000) {
      res = res / 1000;
      return res.toStringAsFixed(2) + "吨";
    } else {
      return res.toStringAsFixed(2) + "千克";
    }
  }

  Future requestInitData() async {
    if (userService.isLogin) {
      EasyLoading.show();
      textEditingControllers = [];
      await HttpClient.request<CartEntity>(
          url: MallApi.cart,
          method: Method.GET,
          params: {
            "dealerId": userService.dealerId,
            "uid": userService.userInfo.uid
          },
          onSuccess: (_, model) async {
            await handle(model);
          },
          onFailed: (err) async {
            EasyLoading.showError(err);
          });
    } else {
//        Get.toNamed(Routes.LOGIN);
    }
  }

  expand(index) {
    // print("展开");
    this.cartList[index].expand = !this.cartList[index].expand;
    cartList.refresh();
  }

  check(CartData item, int index) {
    // print("选中");
    item.checked = !item.checked;
    item.itemList.forEach((e) {
      if (e.checked != item.checked) {
        e.checked = item.checked;
        if (e.checked) {
          chooseList.add(e);
        } else {
          chooseList.remove(e);
        }
      }
    });
    // print(chooseList.length);
    cartList.refresh();
  }

  checkAll() {
    // print("全选中");
    checkAllSelected.value = !checkAllSelected.value;
    if (checkAllSelected.value) {
      cartList.forEach((e) {
        e.checked = true;
        e.itemList.forEach((f) {
          f.checked = true;
          chooseList.add(f);
        });
      });
    } else {
      cartList.forEach((e) {
        e.checked = false;
        e.itemList.forEach((f) {
          f.checked = false;
          chooseList.add(f);
        });
      });
      chooseList = <CartDataItemList>[];
    }
  }

  itemCheck(CartData parent, CartDataItemList item, int index) {
    // print("子选中");
    item.checked = !item.checked;
    if (item.checked) {
      chooseList.add(item);
    } else {
      chooseList.remove(item);
    }
    // print(chooseList.length);
    bool allItemSelect = true;
    //判断父是否被选中
    for (int i = 0; i < parent.itemList.length; i++) {
      if (!parent.itemList[i].checked) {
        allItemSelect = false;
      }
    }
    parent.checked = allItemSelect;
    cartList.refresh();
  }

  cartDelete(CartDataItemList item) {
    showDialog(
        context: Get.context,
        barrierDismissible: false,
        builder: (ctx) {
          return GCDialog(
            title: Text("温馨提示"),
            items: ['取消', '确认'],
            content: '确认删除该产品？',
            onTap: (_) {
              HttpClient.request<CartEntity>(
                  url: MallApi.cart,
                  method: Method.DELETE,
                  data: {
                    "dealerId": userService.dealerId,
                    "uid": userService.userInfo.uid,
                    "item": {
                      "categoryName": item.categoryName,
                      "num": item.num,
                      "skuId": item.skuId,
                      "skuSpec": item.skuSpec
                    }
                  },
                  onSuccess: (_, model) async {
                    requestInitData();
                  },
                  onFailed: (err) async {
                    EasyLoading.showError(err);
                  });
            },
          );
        });
  }

  cartAdd(int x, int y, CartDataItemList item) {
    item.num += 1;
    EasyLoading.show();
    HttpClient.request<CartEntity>(
        url: MallApi.cart,
        method: Method.PUT,
        data: {
          "dealerId": userService.dealerId,
          "uid": userService.userInfo.uid,
          "item": {
            "categoryName": item.categoryName,
            "num": item.num,
            "skuId": item.skuId,
            "skuSpec": item.skuSpec
          }
        },
        onSuccess: (_, model) async {
          EasyLoading.dismiss();
          textEditingControllers[x][y].text = item.num.toString();
        },
        onFailed: (err) async {
          EasyLoading.showError(err);
        });
  }

  cartSub(int x, int y, CartDataItemList item) {
    if (item.num == 1) {
      return;
    }
    item.num -= 1;
    EasyLoading.show();
    HttpClient.request<CartEntity>(
        url: MallApi.cart,
        method: Method.PUT,
        data: {
          "dealerId": userService.dealerId,
          "uid": userService.userInfo.uid,
          "item": {
            "categoryName": item.categoryName,
            "num": item.num,
            "skuId": item.skuId,
            "skuSpec": item.skuSpec
          }
        },
        onSuccess: (_, model) async {
          EasyLoading.dismiss();
          textEditingControllers[x][y].text = item.num.toString();
        },
        onFailed: (err) async {
          EasyLoading.showError(err);
        });
  }

  toMall() {
    GCTabbarController jumpC = Get.find();
    jumpC.updateIndex(1);
  }

  settle() {
    if (chooseList.length == 0) {
      EasyLoading.showError("未选中商品");
    } else {
      EasyLoading.show();
      HttpClient.request<CartSettleEntity>(
          url: MallApi.settle,
          method: Method.POST,
          data: {
            "dealerId": userService.dealerId,
            "uid": userService.userInfo.uid,
            "chooseList": chooseList
          },
          onSuccess: (_, model) async {
            EasyLoading.dismiss();
            Get.toNamed(Routes.SHOPPING_SETTLE, arguments: model);
          },
          onFailed: (err) async {
            EasyLoading.showError(err);
          });
    }
  }

  jumpToLogin() {
    Get.toNamed(Routes.LOGIN);
  }

  changeNum(String v, int x, int y, CartDataItemList sku) {
    // print("$x,$y");
    if (v == '') {
      // print("$originNum");
      v = originNum.toString();
      editChanged = false;
      // print("我啥都没变");
    } else {
      editChanged = true;
    }
    editX = x;
    editY = y;
    editSku = sku;
    editSku.num = int.parse(v);
    // print("我是编号${editSku.skuId}提交了${editSku.num}");
  }

  void directSubmitChange(String v, CartDataItemList item) {
    if (v == '') {
      return;
    }
    EasyLoading.show();
    HttpClient.request<CartEntity>(
        url: MallApi.cart,
        method: Method.PUT,
        data: {
          "dealerId": userService.dealerId,
          "uid": userService.userInfo.uid,
          "item": {
            "categoryName": item.categoryName,
            "num": int.parse(v),
            "skuId": item.skuId,
            "skuSpec": item.skuSpec
          }
        },
        onSuccess: (_, model) async {
          editChanged = null;
          item.num = int.parse(v);
          cartList.refresh();
          EasyLoading.dismiss();
        },
        onFailed: (err) async {
          EasyLoading.showError(err);
        });
  }

  void submitChange() {
    if (editChanged == null) {
      // print("我啥都没干");
      return;
    }
    if (!editChanged) {
      textEditingControllers[editX][editY].text = editSku.num.toString();
      // print("我变回去了");
      return;
    } else {
      EasyLoading.show();
      HttpClient.request<CartEntity>(
          url: MallApi.cart,
          method: Method.PUT,
          data: {
            "dealerId": userService.dealerId,
            "uid": userService.userInfo.uid,
            "item": {
              "categoryName": editSku.categoryName,
              "num": editSku.num,
              "skuId": editSku.skuId,
              "skuSpec": editSku.skuSpec
            }
          },
          onSuccess: (_, model) async {
            EasyLoading.dismiss();
            cartList.refresh();
            editChanged = null;
          },
          onFailed: (err) async {
            EasyLoading.showError(err);
          });
    }
  }

  handle(CartEntity model) {
    EasyLoading.dismiss();
    cartList.assignAll(model.data);
    int temp = 0;
    cartList.forEach((e) {
      temp += e.skuCount;
    });
    skuTotal = temp;
    chooseList = <CartDataItemList>[];
    checkAllSelected.value = false;

    model.data.forEach((e) {
      List<TextEditingController> controllerList = [];
      e.itemList.forEach((i) {
        var controller = TextEditingController.fromValue(TextEditingValue(
            text: '${i.num == null ? "" : i.num}', //判断keyword是否为空
            // 保持光标在最后
            selection: TextSelection.fromPosition(TextPosition(
                affinity: TextAffinity.downstream,
                offset: '${i.num}'.length))));
        controllerList.add(controller);
      });
      textEditingControllers.add(controllerList);
    });

    // print(textEditingControllers);
  }

  void recordOriginNum(int num) {
    originNum = num;
    // print("我是原来的值$originNum");
  }
}
